//实现plugin的事件机制 这里是引入可以监听webpack打包过程中各个节点的事件机制 使用例子
import { SyncHook, AsyncParallelHook } from 'tapable'

class List {
    getRoutes() { 
        console.log('jhsgd');
    }
}

class Car {
    constructor() {
        this.hooks = {
            accelerate: new SyncHook(["newSpeed"]),
            brake: new SyncHook,
            calculateRoutes: new AsyncParallelHook([
                "source",
                "target",
                "routesList",
            ])
        }
    }
    setSpeed(newSpeed) {
        // following call returns undefined even when you returned values
        //触发事件
        this.hooks.accelerate.call(newSpeed);
    }

    useNavigationSystemPromise(source, target) {
        const routesList = new List();
        return this.hooks.calculateRoutes.promise(source, target, routesList).then((res) => {
            // res is undefined for AsyncParallelHook
            return routesList.getRoutes();
        });
    }

    useNavigationSystemAsync(source, target, callback) {
        const routesList = new List();
        this.hooks.calculateRoutes.callAsync(source, target, routesList, err => {
            if (err) return callback(err);
            callback(null, routesList.getRoutes());
        });
    }
}

// 1.先注册
const car = new Car()
//调用hooks函数 tap()是注册一个同步事件 使用call触发 第一个参数test是事件名
//同步调用
car.hooks.accelerate.tap('test', (speed) => {
    console.log("accelerate", speed);
})
//tapPromise 是注册异步promise事件 用promise触发
car.hooks.calculateRoutes.tapPromise("test_premise", (source, target) => {
    console.log('ashkdgkasdh');
    return new Promise((resolve, reject) => {
        setTimeout(() => { 
            console.log('tapPromise',source,target);
            resolve()
        }, 120)
    })
})


// 2.后触发
car.setSpeed(100)//里含call

car.useNavigationSystemPromise([1, 2, 3], 6)//里含promise